package com.sgb.kjwl.viewmodel.home;


import android.content.Context;
import android.text.TextUtils;
import android.util.SparseArray;

import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.ProListEntity;
import com.sgb.kjwl.model.entity.businessmanagement.CompanyEntity;
import com.sgb.kjwl.model.entity.self.CompanyFocusEntity;
import com.sgb.kjwl.model.entity.self.PermissionMenuEntity;
import com.sgb.kjwl.model.entity.transport.CarFilterEntity;
import com.sgb.kjwl.model.entity.transport.CarTypeAndCarLength;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.ManageEntity;
import com.sgb.kjwl.model.entity.transport.ManageListEntity;
import com.sgb.kjwl.model.entity.transport.MapSourcesEntity;
import com.sgb.kjwl.model.entity.transport.VehicleHallMapEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.view.entity.PermissionEntity;
import com.sgb.kjwl.repository.HomeRepertory;
import com.sgb.kjwl.utils.LocationUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.ui.fragment.home.FreightTransportFragment4;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.sgb.kjwl.view.widget.GoodsMoreFilterPopWindow.DEFAULT_GOODS_TYPE;

public class FreightTransportFragModel4 extends BaseViewModel {
    private FreightTransportFragment4 fragment;
    private HomeRepertory repertory;
    public MutableLiveData<List<CarTypeAndCarLength>> typesAndLensLD = new MutableLiveData<>();
    public Map<String, List<CarTypeAndCarLength>> allCarTypeAndCarLengthMap = new HashMap<>();
    public MutableLiveData<CarFilterEntity> ldFilter = new MutableLiveData<>();
    public MutableLiveData<List<VehicleHallMapEntity>> ldCars = new MutableLiveData<>();
    public MutableLiveData<List<MapSourcesEntity>> ldGoods = new MutableLiveData<>();
    public MutableLiveData<List<ManageListEntity>> ldManageList = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarType = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldCarFunction = new MutableLiveData<>();
    public MutableLiveData<List<GoodsInfoTypeEntity3>> ldGoodsType = new MutableLiveData<>();
    public SparseArray<List<AddressEntity>> companyList = new SparseArray<>();
    public MutableLiveData<Boolean> ldGetAllList = new MutableLiveData<>();
    public int typeMenu = 0;

    public FreightTransportFragModel4(FreightTransportFragment4 fragment, HomeRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;
        ldFilter.setValue(new CarFilterEntity());
    }

    public void saveProvinceModel(String name, String code) {
        repertory.setAreaCode(code);
        repertory.setAreaName(name);
    }

    public void getUserInfo() {
        //获取用户数据
        NewAPIManager.getInstance().getLogisticsAPI().getLogisticsPermissions().enqueue(new ICallBack<BaseEntity<PermissionEntity>>() {
            @Override
            public void onSuccess(BaseEntity<PermissionEntity> data) {
                if(data.isSuccess()){
                    UserOperating.getInstance().setUserInfo(data.getData());
                    fragment.startUploadDriverLocation();
                }
            }
        });
    }

    /**
     * 获取我的页面菜单数据
     */
    public void getPermissionMenu(CompanyEntity entity) {
        //返回页面数据
        APIManager.getInstance().getUserAPI().getPermissionMenu(entity.getCompNo(), entity.getType()).enqueue(new Callback<BaseEntity<List<PermissionMenuEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PermissionMenuEntity>>> call, Response<BaseEntity<List<PermissionMenuEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response != null && response.body() != null && response.body().getData() != null) {
                    Gson gson = new Gson();
                    String s = gson.toJson(response.body().getData(), new TypeToken<List<PermissionMenuEntity>>() {
                    }.getType());
                    List<PermissionMenuEntity> list = response.body().getData();
                    fragment.showPermissionMenu(list);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PermissionMenuEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void getCarInfo() {
//        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new Callback<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarInfo>>> call, Response<BaseEntity<List<CarInfo>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    fragment.showCarInfo(response.body().getData());
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarInfo>>> call, Throwable t) {

            }
        });
    }

    /**
     * 判断是否需要完善车辆信息
     * ps：只有一辆车的时候才检测
     */
    public void showcheckCarInfo() {
        DialogHelper.showProgressDialog(fragment.getActivity(), "请求中...");
        APIManager.getInstance().getDriverAPI().getCarInfo().enqueue(new ICallBack<BaseEntity<List<CarInfo>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CarInfo>> data) {
                DialogHelper.dismissProgressDialog();
                if (data == null || data.getData() == null) {
                    return;
                }
                List<CarInfo> carInfos = data.getData();
                if (carInfos.size() > 0) {
                    // 只判断有且只有一辆车的时候车辆信息是否完善
                    boolean needComplete;
                    if (carInfos.size() == 1 && carInfos.get(0) != null) {
                        if (carInfos.get(0).getIsComplete() == 1) {
                            needComplete = false;
                        } else {
                            needComplete = true;
                        }
                    } else {
                        needComplete = false;
                    }
                    if (!needComplete) {
                        fragment.showCarInfoResult(true, null);
                    } else {
                        fragment.showCarInfoResult(false, carInfos.get(0));
                    }
                }
            }
        });
    }

    public void getCarTypeAndCarLengthList(String goodsTypeNo) {
        if (TextUtils.isEmpty(goodsTypeNo) || goodsTypeNo.equals(DEFAULT_GOODS_TYPE)) {
            goodsTypeNo = "";
        }
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        String finalGoodsTypeNo = goodsTypeNo;
        String finalGoodsTypeNo1 = goodsTypeNo;
        APIManager.getInstance().getDriverAPI().getCarTypeAndCarLengthList(goodsTypeNo).enqueue(new Callback<BaseEntity<List<CarTypeAndCarLength>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Response<BaseEntity<List<CarTypeAndCarLength>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null)
                    return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    setCarTypeAndCarLength(finalGoodsTypeNo1, response.body().getData());
                } else {
                    MToast.showToast(fragment.getActivity(), response.body().getState());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<CarTypeAndCarLength>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 储存请求下来的  相应货源类型的车型车长信息，避免多次重复请求
     *
     * @param goodsTypeNo
     * @param list
     */
    public void setCarTypeAndCarLength(String goodsTypeNo, List<CarTypeAndCarLength> list) {
        if (list == null) return;
        if (!isContainCarTypeAndCarLengthByGoodsNo(goodsTypeNo)) {
            allCarTypeAndCarLengthMap.put(goodsTypeNo, list);
        }
        typesAndLensLD.postValue(list);
    }

    public boolean isContainCarTypeAndCarLengthByGoodsNo(String goodsNo) {
        if (goodsNo == null) {
            return false;
        }
        return allCarTypeAndCarLengthMap.keySet().contains(goodsNo);
    }


    /**
     * 从地图获取车辆
     */
    public void getCarFormMap(Context context) {
        //判断筛选条件
        if (ldFilter.getValue() == null) return;
        Map<String, Object> map = new HashMap<>();
        if (LocationUtil.isOpenLocation(context) && LocationUtil.currentLocationIsValid()) {
            map.put("isAuthorization", 1);
            //设置当前定位经纬度
        } else {
            map.put("isAuthorization", 0);
        }
        map.put("radius", 0);
        //当前查找经纬度
        map.put("searchLongitude", ldFilter.getValue().getLongitude());
        map.put("searchLatitude", ldFilter.getValue().getLatitude());
        map.put("page", 1);
        map.put("limit", 50);
        map.put("keyWord", "");
        map.put("needVideo", 0);
        DialogHelper.showProgressDialog(context, "数据获取中...").setCanceledOnTouchOutside(false);
        NewAPIManager.getInstance().getLogisticsAPI().getCarToMap(map).enqueue(new ICallBack<BaseEntity<ProListEntity<List<VehicleHallMapEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<VehicleHallMapEntity>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data == null || data.getData() == null) {
                    return;
                }
                if (data.getData().getList() == null) {
                    return;
                }
                //刷新数据，添加地图marker
                ldCars.postValue(data.getData().getList());
            }
        });
    }


    /**
     * 地图获取找货数据
     *
     * @param context
     */
    public void getGoodsSourceList(Context context) {
        DialogHelper.showProgressDialog(context, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        Map map = new HashMap();
        map.put("page", 1);
        map.put("limit", 50);
        map.put("needVideo", "0");
        map.put("searchLongitude", ldFilter.getValue().getLongitude());
        map.put("searchLatitude", ldFilter.getValue().getLatitude());
        map.put("radius", 0);
        NewAPIManager.getInstance().getLogisticsAPI().getMapSourceList(map).enqueue(new ICallBack<BaseEntity<ProListEntity<List<MapSourcesEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ProListEntity<List<MapSourcesEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.getData() == null || response.getData().getList() == null) return;
                ldGoods.postValue(response.getData().getList());
            }
        });
    }

    /**
     * 获取会员列表
     */
    public void getLeaguerList(int type) {
        NewAPIManager.getInstance().getLogisticsAPI().getMemberByType(type).enqueue(new ICallBack<BaseEntity<ManageEntity<List<ManageListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ManageEntity<List<ManageListEntity>>> data) {
                List<AddressEntity> list = new ArrayList<>();
                if (data.getState().equals("ok")) {
                    if (data.getData() == null || data.getData().getMember() == null) {
                        ldManageList.postValue(new ArrayList<>());
                        if (type == 1) {
                            companyList.append(1, list);
                        } else {
                            companyList.append(2, list);
                        }
                        return;
                    }

                    for (ManageListEntity memberCompanyEntity : data.getData().getMember()) {
                        AddressEntity pickFilterEntity = new AddressEntity();
                        pickFilterEntity.setName(memberCompanyEntity.getCompanyName());
                        pickFilterEntity.setNo(memberCompanyEntity.getCompanyNo());
                        list.add(pickFilterEntity);
                    }
                    if (type == 1) {
                        typeMenu = 3;
                        companyList.append(1, list);
                    } else {
                        typeMenu = 2;
                        companyList.append(2, list);
                    }
                    ldManageList.postValue(data.getData().getMember());
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }


            @Override
            public void onFailure(Call<BaseEntity<ManageEntity<List<ManageListEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    /**
     * 获取关注列表
     *
     * @param page
     * @param userNo
     */
    public void getAttendCompanyList(int page, String userNo) {
        APIManager.getInstance().getUserAPI().getCompanyFocus(page, 27, userNo).enqueue(new Callback<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> call, Response<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null || response.body().getData().getList() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK) && response.body().getData() != null) {
                    typeMenu = 1;
                    List<AddressEntity> list = new ArrayList<>();
                    for (CompanyFocusEntity memberCompanyEntity : response.body().getData().getList()) {
                        AddressEntity pickFilterEntity = new AddressEntity();
                        pickFilterEntity.setName(memberCompanyEntity.getCompanyName());
                        pickFilterEntity.setNo(memberCompanyEntity.getCompanyNo());
                        list.add(pickFilterEntity);
                    }
                    companyList.append(3, list);

                    List<ManageListEntity> list1 = new ArrayList<>();
                    for (CompanyFocusEntity memberCompanyEntity : response.body().getData().getList()) {
                        ManageListEntity pickFilterEntity = new ManageListEntity();
                        pickFilterEntity.setCompanyName((memberCompanyEntity.getCompanyName()));
                        pickFilterEntity.setCompanyNo(memberCompanyEntity.getCompanyNo());
                        list1.add(pickFilterEntity);
                    }
                    ldManageList.postValue(list1);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    /**
     * 获取会员列表或成员列表
     */
    public void getLeaguerOrVipList(int type) {
        NewAPIManager.getInstance().getLogisticsAPI().getMemberByType(type).enqueue(new ICallBack<BaseEntity<ManageEntity<List<ManageListEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ManageEntity<List<ManageListEntity>>> data) {
                List<AddressEntity> list = new ArrayList<>();
                if (data.getState().equals("ok")) {
                    if (data.getData() == null || data.getData().getMember() == null) {

                        if (type == 1) {
                            companyList.append(1, list);
                            getLeaguerOrVipList(2);
                        } else {
                            companyList.append(2, list);
                            getMyAttendCompanyList(1, SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
                        }
                        return;
                    }

                    for (ManageListEntity memberCompanyEntity : data.getData().getMember()) {
                        AddressEntity pickFilterEntity = new AddressEntity();
                        pickFilterEntity.setName(memberCompanyEntity.getCompanyName());
                        pickFilterEntity.setNo(memberCompanyEntity.getCompanyNo());
                        list.add(pickFilterEntity);
                    }
                    if (type == 1) {
                        companyList.append(1, list);
                        getLeaguerOrVipList(2);
                    } else {
                        companyList.append(2, list);
                        getMyAttendCompanyList(1, SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
                    }
                } else {
//                    MToast.showToast(activity, response.body().getMsg());
                }
            }


            @Override
            public void onFailure(Call<BaseEntity<ManageEntity<List<ManageListEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                if (type == 1) {
                    companyList.append(1, new ArrayList<>());
                    getLeaguerOrVipList(2);
                } else {
                    companyList.append(2, new ArrayList<>());
                    getMyAttendCompanyList(1, SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""));
                }
            }
        });
    }

    /**
     * 获取关注列表
     *
     * @param page
     * @param userNo
     */
    public void getMyAttendCompanyList(int page, String userNo) {
        APIManager.getInstance().getUserAPI().getCompanyFocus(page, 27, userNo).enqueue(new Callback<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> call, Response<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                List<AddressEntity> list = new ArrayList<>();
                if (response.body() == null || response.body().getState() == null || response.body().getData().getList() == null) {
                    companyList.append(3, list);
                    ldGetAllList.postValue(false);
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK) && response.body().getData() != null) {

                    for (CompanyFocusEntity memberCompanyEntity : response.body().getData().getList()) {
                        AddressEntity pickFilterEntity = new AddressEntity();
                        pickFilterEntity.setName(memberCompanyEntity.getCompanyName());
                        pickFilterEntity.setNo(memberCompanyEntity.getCompanyNo());
                        list.add(pickFilterEntity);
                    }
                    companyList.append(3, list);
                    ldGetAllList.postValue(true);

                }
            }

            @Override
            public void onFailure(Call<BaseEntity<com.swgk.core.base.model.entity.ListResponse<List<CompanyFocusEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                ldGetAllList.postValue(false);
                companyList.append(3, new ArrayList<>());
            }
        });
    }

    /**
     * 获取车型
     */
    public void getCarTypeList() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllCarType().enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if (data.getData() == null) {
                    data.setData(new ArrayList<>());
                }
                ldCarType.postValue(data.getData());
            }
        });
    }

    /**
     * 获取车辆功能列表
     */
    public void getCarFunction() {
        NewAPIManager.getInstance().getLogisticsAPI().getCarFunction().enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if (data.getData() == null) {
                    data.setData(new ArrayList<>());
                }
                ldCarFunction.postValue(data.getData());
            }
        });
    }

    /**
     * 获取货源类型
     */
    public void getGoodsType() {
        NewAPIManager.getInstance().getLogisticsAPI().getAllGoodsType().enqueue(new ICallBack<BaseEntity<List<GoodsInfoTypeEntity3>>>() {
            @Override
            public void onSuccess(BaseEntity<List<GoodsInfoTypeEntity3>> data) {
                if (data.getData() == null) {
                    data.setData(new ArrayList<>());
                }
                ldGoodsType.postValue(data.getData());
            }
        });

    }

    /**
     * 这是用来获取物流首页的顶部标题的
     *
     * @return 物流首页的数据
     */
    public List<Integer> getContentTitle() {
        List<Integer> mTitleData = new ArrayList<>();
        mTitleData.add(R.mipmap.home_item_hydt);
        mTitleData.add(R.mipmap.home_item_hcdt);
        mTitleData.add(R.mipmap.home_item_jjhy);
        mTitleData.add(R.mipmap.home_item_sjzh);
        mTitleData.add(R.mipmap.home_item_zyxs);
        mTitleData.add(R.mipmap.home_item_zyfw);
        mTitleData.add(R.mipmap.home_item_hyjy);
        return mTitleData;
    }
}
